<?php
class GroupsController extends AppController {
	var $name = 'Groups';
	var $uses = array('Group');
	var $layout = 'admin';
	var $helpers = array('Html', 'Javascript', 'Form', 'Time');
	var $components = array('General');
	
	function index() {
		$condition = array();
		//Set id for case to edit
		$group_id = null;
		
		//Get variable from url params
		if (!empty($this->passedArgs))
		{
			if (isset($this->passedArgs['Search.name']))
			{
				$condition[]["Group.name LIKE"] = "%{$this->passedArgs['Search.name']}%";
				$this->data['Search']['name'] = $this->passedArgs['Search.name'];
			}
			if (isset($this->passedArgs['Category.cat_id']))
			{
				$group_id = $this->passedArgs['Category.cat_id'];
				unset($this->passedArgs['Category.cat_id']); 
			}
		}
		//Save or edit data
		if (!empty($this->data) && isset($this->data['Group']))
		{
			$this->Group->id = $group_id;
			if ($this->Group->save($this->data))
			{
				$this->Session->setFlash('Group đã được sửa');
				
				//Unset data group
				unset($this->data['Group']);
				unset($this->passedArgs[0]);
				
				//Set agains url
				$url = $this->passedArgs;
				$url['action'] = 'index';
				$this->redirect($url, null, true);
			} else {
				$this->Session->setFlash('Lưu thông tin thất bại');
			}
		} 
		if (!isset($this->data['Group']))
		{
			$this->data = $this->Group->findById($group_id);
		}
		
		//Get data for view index
		$this->Groups->recursive = 1;
		$this->paginate = array('limit' => 15, 'page' => 1, 'order' => array('Group.created' => 'desc'));
		$groups = $this->paginate('Group', $condition);
		$this->set('groups', $groups);	
	}
	
	function delete($id = null)
	{
		if (!$id)
		{
			$this->Session->setFlash('Không đúng ID');
			$this->redirect ('index');
		}
		if ($this->Group->del($id))
		{
			$this->Session->setFlash('Đã xóa xong');
		}
		$this->redirect('index');
	}
	
}
?>
